package Threadtest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class test6_wait {
    public static void main(String[] args) {
        Cook cook = new Cook();
        Food food = new Food();

        Thread c=new Thread(cook);
        Thread f=new Thread(food);

        c.setName("厨师");
        f.setName("食客");

        c.start();
        f.start();
    }
}
class Desk{
    //
static final Lock lock=new ReentrantLock();
//0无面条 1有面条
static int foodflag=0;
static int count=10;

}
class Cook implements Runnable{
    @Override
    public void run() {
        while (true){
            synchronized (Desk.lock){
                if (Desk.count<0){
                    break;
                }else {
                    if (Desk.foodflag==1){
                        try {
                            Desk.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        System.out.println("厨师做了一碗面条");
                        Desk.foodflag=1;
                        //叫醒食客来吃
                        Desk.lock.notifyAll();

                    }
                }
            }
        }
    }
}
class Food implements Runnable{
    @Override
    public void run() {
        while (true){
            synchronized (Desk.lock){
                if (Desk.count<=0){
                    break;
                }
                else {
                    if (Desk.foodflag==0){
                        try {
                            //当前线程与锁绑定
                            Desk.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        Desk.count--;
                        System.out.println("陈慧萱还能吃"+Desk.count+"碗");
                        //吃完之后唤醒厨师继续做
                        Desk.lock.notifyAll();
                        Desk.foodflag=0;
                    }
                }
            }
        }
    }
}
